import {
    getSubdirectoriesSync,
    omitIndex,
    TineConfigure,
    transformCssModuleName
} from '@tencent/rollup-config-tine';
import { basename, normalize, resolve } from 'path';

const externalPatterns = [/^react/, /^react-dom/, /^@material/, /^@babel/, /^@tarojs\/\w+$/];
const entryList = getSubdirectoriesSync(resolve('./src/components'));
const setExternal = (id: string) => {
    const isStyleFile = ['css', '.scss'].some((ext) => id.endsWith(ext));
    if (isStyleFile) {
        return false;
    }
    const isExternalDep = externalPatterns.some((pattern) => pattern.test(id));
    if (isExternalDep) {
        return true;
    }
    if (id.startsWith('.') && !id.includes('node_modules') && !id.includes('components')) {
        const dirName = basename(normalize(id));
        if (entryList.includes(dirName) && /^(\.\.\/)+[a-zA-Z-]+$/.test(id)) {
            return true;
        }
    }
    return false;
};
export default {
    libType: 'pattern',
    entry: {
        filename: '[dir]',
        ignore: ['**/node_modules/**', '**/src/index.ts'],
        pattern: './src/components/*/index.{ts,tsx}'
    },

    output: {
        exports: 'named',
        dir: 'dist/es',
        format: 'esm',
        chunkFileNames: 'common/[name].js',
        entryFileNames: (chunInfo) => {
            const { type, name } = chunInfo;
            if (type === 'chunk' && /index\.scss$/.test(name)) {
                return name.replace(/index\.scss$/, 'style/index.js');
            }
            return '[name]/index.js';
        },
        globals: {
            react: 'react',
            'react-dom': 'reactDom',
            'react/jsx-runtime': 'reactJsxRuntime',
            'react/jsx-dev-runtime': 'reactJsxDevRuntime'
        },
        assetFileNames(chunInfo) {
            const { type, name = '' } = chunInfo;
            if (type === 'asset' && /\.css$/.test(name || '')) {
                return '[name]/index[extname]';
            }
            return '[name]/[extname]';
        }
    },
    scssModule: {
        modules: {
            naming: 'camelCase',
            generateScopedName: transformCssModuleName('k')
        },
        extensions: ['.css', '.scss'],
        mode: ['extract']
    },
    external: setExternal,
    build: {
        babelType: 'react-lib',
        target: process.env.NODE_ENV === 'production' ? 'es6' : 'es6',
        isMinify: process.env.NODE_ENV === 'production',
        style: {
            entry: './src/components/*/index.{ts,tsx}'
        }
    },
    declaration: {
        entry: {
            filename: '[dir]',
            pattern: './src/components/*/index.{ts,tsx}'
        },
        output: {
            dir: './dist/es',
            entryFileNames: omitIndex('[name]/index.d.ts'),
            chunkFileNames: 'common/[name].ts'
        }
    }
} satisfies TineConfigure;
